// Copyright (c) 2021 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

package matching

import (
	"testing"

	gomock "github.com/golang/mock/gomock"
	"github.com/stretchr/testify/assert"

	"github.com/uber/cadence/common/membership"
	"github.com/uber/cadence/common/service"
)

func TestPeerResolver(t *testing.T) {
	controller := gomock.NewController(t)
	serviceResolver := membership.NewMockResolver(controller)
	host1 := membership.NewDetailedHostInfo(
		"tasklistHost:1234",
		"tasklistHost_1234",
		membership.PortMap{
			membership.PortTchannel: 1234,
			membership.PortGRPC:     1244,
		},
	)
	host2 := membership.NewDetailedHostInfo(
		"tasklistHost2:1235",
		"tasklistHost2_1235",
		membership.PortMap{
			membership.PortTchannel: 1235,
			membership.PortGRPC:     1245,
		},
	)
	serviceResolver.EXPECT().Lookup(service.Matching, "taskListA").Return(
		host1,
		nil)
	serviceResolver.EXPECT().Lookup(service.Matching, "invalid").Return(membership.HostInfo{}, assert.AnError)
	serviceResolver.EXPECT().LookupByAddress(service.Matching, "invalid address").Return(membership.HostInfo{}, assert.AnError)

	serviceResolver.EXPECT().Members(service.Matching).Return([]membership.HostInfo{
		host1,
		host2,
	}, nil)

	serviceResolver.EXPECT().LookupByAddress(service.Matching, "tasklistHost2:1235").Return(
		host2,
		nil,
	).AnyTimes()
	serviceResolver.EXPECT().LookupByAddress(service.Matching, "tasklistHost:1234").Return(
		host1,
		nil,
	).AnyTimes()
	r := NewPeerResolver(serviceResolver, membership.PortGRPC)

	peer, err := r.FromTaskList("taskListA")
	assert.NoError(t, err)
	assert.Equal(t, "tasklistHost:1244", peer)

	_, err = r.FromTaskList("invalid")
	assert.Error(t, err)

	_, err = r.FromHostAddress("invalid address")
	assert.Error(t, err)

	peers, err := r.GetAllPeers()
	assert.NoError(t, err)
	assert.Equal(t, []string{"tasklistHost:1244", "tasklistHost2:1245"}, peers)

}
